package com.example.springboot1.limit;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.example.springboot1.entity.FillData;
import com.example.springboot1.utils.BussinessException;
import com.example.springboot1.utils.FileUtil;
import com.example.springboot1.utils.HttpKit;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author ckj
 * @description TODO
 * @date 2023-03-10 8:58
 */

@RestController
public class LimitApi {
    @Autowired
    private LimitService limitService;

    @RequestMapping("/access")
    public ResponseEntity<byte[]> access() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //尝试获取令牌
        if (limitService.tryAcquire()) {
            //模拟业务执行500毫秒
            try {
                ExecutorService executor = new ThreadPoolExecutor(10, 10,
                        60L, TimeUnit.SECONDS,
                        new ArrayBlockingQueue(10));
                //返回Future，实际上是FutureTask实例
                DownWork downWork=new DownWork();
                Future<ResponseEntity<byte[]>> future = executor.submit(downWork);
                return future.get();
            } catch (Exception e) {
                e.printStackTrace();
                throw new BussinessException("");
            }
        } else {
            throw new BussinessException("");
        }
    }

    public String getTest() {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        //定义Callable
        Callable<String> callable = new Callable() {
            @Override
            public Object call() throws Exception {
                return "test";
            }
        };
        //返回Future，实际上是FutureTask实例
        Future<String> future = pool.submit(callable);
        try {
            return future.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
            throw new BussinessException("文件下载失败");
        } catch (InterruptedException e) {
            e.printStackTrace();

            throw new BussinessException("文件下载失败");

        }
    }


     public String getWork() {
        //创建线程池
        ExecutorService pool = Executors.newSingleThreadExecutor();
        //定义Callable
        Callable<String> callable = new Callable() {
            @Override
            public Object call() {
                return dowrite();

            }
        };
        //返回Future，实际上是FutureTask实例
        Future<String> future = pool.submit(callable);
        try {
//            TimeUnit.SECONDS.sleep(2);
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BussinessException("文件下载失败");
        }
    }


    public String dowrite() {
        // 写法1
        String fileName = FileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("templates/dd.xlsx");
        //读取Excel
        ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(resourceAsStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();

        FillData fillData = new FillData();
        fillData.setName("张三");
        fillData.setNumber(5.2);
        excelWriter.fill(fillData, writeSheet);
        List<FillData> data = new ArrayList<>();
        data.add(fillData);
        data.add(fillData);
        FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
        excelWriter.fill(data, fillConfig, writeSheet);

        Map<String, Object> map = new HashMap<>();
        map.put("date", "2019年10月9日13:28:28");
        excelWriter.fill(map, writeSheet);

        return fileName;
    }


    public ResponseEntity<byte[]> work() {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();


            InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("templates/dd.xlsx");
            //读取Excel
            ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(resourceAsStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();

            FillData fillData = new FillData();
            fillData.setName("张三");
            fillData.setNumber(5.2);
            excelWriter.fill(fillData, writeSheet);
            List<FillData> data = new ArrayList<>();
            data.add(fillData);
            data.add(fillData);
            FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
            excelWriter.fill(data, fillConfig, writeSheet);

            Map<String, Object> map = new HashMap<>();
            map.put("date", "2019年10月9日13:28:28");
            excelWriter.fill(map, writeSheet);

            excelWriter.finish();
            byte[] bytes = out.toByteArray();

            String fileName = "xx.xlsx";
            HttpHeaders headers = new HttpHeaders();

            String userAgent = HttpKit.getRequest().getHeader("User-Agent");
            if (userAgent.toLowerCase().indexOf("trident") > -1
                    || userAgent.toLowerCase().indexOf("edge") > -1) {// IE，Edge浏览器
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            headers.add("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            HttpStatus httpStatus = HttpStatus.OK;

            return new ResponseEntity(bytes, headers, httpStatus);
        } catch (UnsupportedEncodingException e) {
            throw new BussinessException("文件下载失败");
        }


    }
}
